package com.design.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.design.config.CommonException;
import com.design.dao.entity.Template;
import com.design.dao.mapper.TemplateMapper;
import com.design.model.PageResult;
import com.design.service.TemplateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
public class TemplateServiceImpl implements TemplateService {

    @Autowired
    private TemplateMapper templateMapper;

    @Override
    public PageResult<List<Template>> queryByPage(String templateNum, Integer pageNum, Integer pageSize) {
        QueryWrapper<Template> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", 0);
        wrapper.orderByDesc("id");
        if (StringUtils.isNoneBlank(templateNum)) {
            wrapper.eq("template_num", templateNum);
        }
        Page<Template> responseList = templateMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return new PageResult<>(responseList.getRecords(), responseList.getTotal());
    }

    @Override
    public void edit(Template template) {
        template.setIsDelete((byte)0);
        if (null == template.getId()) {
            QueryWrapper<Template> templateQueryWrapper = new QueryWrapper<>();
            templateQueryWrapper.eq("template_num", template.getTemplateNum());
            List<Template> templates = templateMapper.selectList(templateQueryWrapper);
            if (!CollectionUtils.isEmpty(templates)) {
                throw new CommonException("车板号已存在，请勿重复录入");
            }

            template.setCreateTime(new Date());
            templateMapper.insert(template);
            return;
        }
        templateMapper.updateById(template);
    }

    @Override
    public void remove(Integer id) {
        templateMapper.deleteById(id);
    }
}
